
<template>
  <div class="order-list-view">
    <div class="header">
      <h1>订单管理</h1>
    </div>

    <div class="filters">
      <el-select v-model="filterStatus" placeholder="筛选订单状态" @change="fetchOrders" clearable>
        <el-option label="全部" value=""></el-option>
        <el-option label="待处理" value="PENDING"></el-option>
        <el-option label="已支付" value="PAID"></el-option>
        <el-option label="已取消" value="CANCELLED"></el-option>
        <el-option label="已发货" value="SHIPPED"></el-option>
        <el-option label="已完成" value="COMPLETED"></el-option>
      </el-select>
    </div>

    <el-table :data="orders" v-loading="loading" style="width: 100%">
      <el-table-column prop="id" label="订单ID" width="100"></el-table-column>
      <el-table-column prop="userId" label="用户ID" width="100"></el-table-column>
      <el-table-column prop="totalPoints" label="总积分" width="120"></el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="statusTagType(row.status)">{{ row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" width="180"></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="handleViewDetails(row)">详情</el-button>
          <el-dropdown @command="(command: string) => handleUpdateStatus(row, command)">
            <el-button size="small" type="primary">
              更新状态 <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="PAID">设为已支付</el-dropdown-item>
                <el-dropdown-item command="SHIPPED">设为已发货</el-dropdown-item>
                <el-dropdown-item command="COMPLETED">设为已完成</el-dropdown-item>
                <el-dropdown-item command="CANCELLED">设为已取消</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      @current-change="handlePageChange"
      class="pagination"
    >
    </el-pagination>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import type { Order } from '@/types'
import { getAdminOrderList, updateOrderStatus } from '@/api/modules/order'

const router = useRouter()

const orders = ref<Order[]>([])
const loading = ref(false)
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const filterStatus = ref('')

const fetchOrders = async () => {
  try {
    loading.value = true
    const params = { 
      page: page.value, 
      size: pageSize.value, 
      status: filterStatus.value || undefined 
    }
    const response = await getAdminOrderList(params)
    orders.value = response.list
    total.value = response.total
  } catch (error) {
    ElMessage.error('获取订单列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handlePageChange = (currentPage: number) => {
  page.value = currentPage
  fetchOrders()
}

const handleViewDetails = (order: Order) => {
  router.push(`/admin/orders/${order.id}`)
}

const handleUpdateStatus = async (order: Order, status: string) => {
  try {
    await ElMessageBox.confirm(`确定要将订单 ${order.id} 的状态更新为 ${status} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await updateOrderStatus(order.id, status)
    ElMessage.success('订单状态更新成功')
    fetchOrders() // Refresh list
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('订单状态更新失败')
      console.error(error)
    }
  }
}

const statusTagType = (status: string) => {
  switch (status) {
    case 'PENDING': return 'warning'
    case 'PAID': return ''
    case 'SHIPPED': return 'primary'
    case 'COMPLETED': return 'success'
    case 'CANCELLED': return 'info'
    default: return 'info'
  }
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.filters {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
